/*
 * =====================================================================================
 *
 *       Filename:  cl_tcp_conn.hxx
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  03/29/2011 03:24:33 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Ken Chen (Ken), chen_kenz@emc.com
 *        Company:  EMC
 *
 * =====================================================================================
 */

#ifndef _CL_TCP_CONN_HXX_
#define _CL_TCP_CONN_HXX_

#include <atomic>
#include <memory>
#include <string>
#include "cl_socket_addr.hxx"
#include "cl_net_callback.hxx"

namespace neo
{
class CLChannel;
class CLSocket;
class CLEventLooper;
class CLTcpConn: public std::enable_shared_from_this<CLTcpConn>
{
public:
  CLTcpConn(CLEventLooper* ioLooper,
            int connId,
            int connfd, 
            CLSocketAddrUPtr peerAddr);
  ~CLTcpConn();
  bool send(const std::string& msg);
  bool send(const void* data, size_t siz);
	bool shutDownWrite(void);
	bool shutDownRead(void);
	bool shutDown(void);
  void handleEstablished(void);
  void handleDestroy(void); 
  void handleRead(void);
  void handleWrite(void);
  void handleClose(void);
  void handleError(void);
	int connId(void) const;
	CLEventLooper* ioLooper(void);

public:
  void sendInLooper(const void* data, size_t siz);
  void setConnCallback(const CLConnCallback& cb);
  void setMessageCallback(const CLMessageCallback& cb);
  void setWriteCompleteCallback(const CLWriteCompleteCallback& cb);
  void setCloseCallback(const CLCloseCallback& cb);

private:
  enum CLTcpState
  {
    TCP_CONNECTING,
    TCP_CONNECTED,
    TCP_DISCONNECTING,
    TCP_DISCONNECTED,
  };

private:
  void setState(CLTcpState st);

private:
	CLTcpConn(const CLTcpConn&);
	CLTcpConn& operator=(const CLTcpConn&);

private:
  CLEventLooper* m_ioLooper;
	int m_connId;
  std::unique_ptr<CLSocket> m_socket;
  std::unique_ptr<CLChannel> m_ioChannel;
  std::atomic<int> m_curState;
  CLConnCallback m_connCallback;
	CLMessageCallback m_msgCallback;
	CLWriteCompleteCallback m_writeCompleteCallback;
	CLCloseCallback m_closeCallback;
};

typedef std::shared_ptr<CLTcpConn> CLTcpConnSPtr;
} // neo

#endif //_CL_TCP_CONN_HXX_

